<template>
    <div class="system-tenant-container">
        <el-dialog title="新增租户" v-model="isShowDialog" >
            <el-form ref="addTenantFormRef" :model="formData" :rules="formRules" label-width="100px">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="租户号码" prop="id">
                            <el-input v-model="formData.id" placeholder="请输入租户号码" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="租户名称" prop="tenantName">
                            <el-input v-model="formData.tenantName" placeholder="请输入租户名称" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="关联数据源" prop="datasourceId">
                            <el-select v-model="formData.datasourceId" filterable remote 
                                @click="loadDatasourceData()"
                                :remote-method="loadDatasourceData" placeholder="请选择关联数据源" clearable class="w100">
								<el-option 
									v-for="item in datasources"
									:key="item.id"
									:label="item.name"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col>
						<el-form-item label="授权菜单权限">
							<el-cascader
								placeholder="请选择菜单权限（可选填）"
								v-model="formData.menuIds"
								:options="menus"
								:props="{expandTrigger: 'hover', multiple: true, value: 'id', label: 'menuName', children: 'children' }"
								collapse-tags
								class="w100"
								clearable>
							</el-cascader>
						</el-form-item>
					</el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="formData.status" placeholder="请选择状态" clearable class="w100">
								<el-option label="正常" value="0"></el-option>
								<el-option label="停用" value="1"></el-option>
								<el-option label="删除" value="2"></el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="备注" prop="remark">
                            <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="onCancel">取 消</el-button>
                    <el-button type="primary" @click="onSubmit">保 存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { addTenant } from '/@/api/system/tenant/index';
import { getMenuList } from '/@/api/system/menu/index';
import { getDatasourceList } from '/@/api/system/datasource/index';
import { lineToTreeData } from '/@/utils/commonFunction';
export default {
    name: 'system/tenant/add',
    setup(props, context) {
        const addTenantFormRef = ref();
        const state = reactive({
            isShowDialog: false,
            datasources: [],
            menus: [],
            formData: {
                status: '0',
                menuIds: [],
            },
            formRules : {
                id: { required: true, message: '租户编码不能为空', trigger: 'blur' },
                tenantName: { required: true, message: '租户名称不能为空', trigger: 'blur' },
            }
        });

        
        // 打开弹窗
        const openDialog = (row?: object) => {
            state.isShowDialog = true;
            loadMenuData();
        };
        // 关闭弹窗
        const closeDialog = (row?: object) => {
            state.isShowDialog = false;
            for(var key in state.formData) {
                state.formData[key] = undefined;
            }
            addTenantFormRef.value.resetFields();
            state.formData.menuIds = [];
        };
        // 取消
        const onCancel = () => {
            closeDialog();
        };
        // 新增
        const onSubmit = () => {
            addTenantFormRef.value.validate(valid => {
                if(valid){
                    let menuIds = [];
					state.formData.menuIds.forEach(items => {
						if(typeof items == 'string'){
							menuIds.push(items);
						}else{
							items.forEach(item => {
								menuIds.push(item);
							});
						}
					});
					menuIds = Array.from(new Set(menuIds));//去重

                    let params = {
                        id: state.formData.id,
                        tenantName: state.formData.tenantName,
                        datasourceId: state.formData.datasourceId,
                        status: state.formData.status,
                        remark: state.formData.remark,
                        menuIds: menuIds,
                    }
                    addTenant(params).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('保存成功');
                            context.emit('submit');
                            closeDialog();
                        }
                    });
                }
            });
        };

        const loadDatasourceData = (query?: string) => {
            getDatasourceList({name: query}).then((res) => {
                if(res.code === 0){
                    state.datasources = res.data;
                }
            });
        };

        const loadMenuData = async () => {
			await getMenuList({isTenant: 'N'}).then((res) => {
				if(res.code == 0){
					state.menus = lineToTreeData(res.data);
				}
			});
		}

        return {
            addTenantFormRef,
            openDialog,
            closeDialog,
            onCancel,
            onSubmit,
            loadDatasourceData,
            ...toRefs(state),
        };
    },
};
</script>